$(function () {
    vm.getInfo();

    /*
    new AjaxUpload('#upload', {
        action: baseURL + "ede/project/uploadMusic?id="+vm.id,
        name: 'file',
        autoSubmit: true,
        responseType: "json",
        onSubmit: function (file, extension) {
            if (vm.config.type == null) {
                alert("云存储配置未配置");
                return false;
            }
            if (!(extension && /^(mp3|mp4)$/.test(extension.toLowerCase()))) {
                alert('只支持mp3格式的音乐！');
                return false;
            }
        },
        onComplete : function(file, r){
            if(r.code == 0){
                var audio = vm.$refs.audioExample;
                audio.src = r.url;
                alert("上传成功！");
                //vm.reload();
            }else{
                alert(r.msg);
            }
        }
    });
*/

    new AjaxUpload('#uploadGroup', {
        action: baseURL + "ede/group/impGroup?id="+vm.id+"&name="+vm.selectedAction,
        name: 'file',
        autoSubmit: true,
        responseType: "text",
        onSubmit: function (file, extension) {
            if (vm.config.type == null) {
                alert("云存储配置未配置");
                return false;
            }
            if (!(extension && /^(xml)$/.test(extension.toLowerCase()))) {
                alert('只支持xml的格式！');
                return false;
            }
        },
        onComplete : function(file, xml){
            console.log(xml);
            OpenBlocks(xml);
            vm.saveBlock(null);
            layer.msg("导入成功", {icon: 1});

            /*if(r.code == 0){
                console.log(r.xml);
                OpenBlocks(r.xml);
                vm.saveBlock(null);
                layer.alert("上传成功！");
            }else{
                layer.alert(r.msg);
            }*/
        }
    });

});



var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
        actionList: [],
        current: 0,
		selectedAction: "动作组1",
        beginP: "0",
        endP: "0",
        playstr: "循环播放",
        config: {},
        group: {},
        id: "",  //工程
        project: {}
	},

    created: function(){
	    this.id = this.getUrlKey("id");
        //parent.vm.projectId = this.id;
        //parent.vm.setProjectId(this.id);
        parent.vm.getProjectById(this.id);
        this.getProjectById (this.id);
        this.getConfig();
    },

	methods: {
        getUrlKey: function (name) {
            return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
        },

        getConfig: function () {
            $.getJSON(baseURL + "sys/oss/config", function(r){
                vm.config = r.config;
            });
        },

		//查询左侧动作组
		getInfo: function(){
			var id = $("#id").val();
			$.get(baseURL + "ede/project/selectActions?id="+id, function(r){
				console.log(r.actionList);
                vm.actionList = r.actionList;

                //查询动作组代码
                $.get(baseURL + "ede/group/oneGroup?id="+id+"&actionname="+vm.selectedAction, function(r){
                    //console.log(r.group);
                    if(r.group.xml) {
                        console.log("11");
                        //block加载文件
                        OpenBlocks(r.group.xml);
                    }else{
                        console.log("22");
                        //加载空文件
                        OpenBlocks("");
                    }
                });

            });
		},

		//查询动作组对应代码
        selected: function (index,event) {
            //首先获取上一个动作组
            var lastAction = vm.selectedAction;
            //控制样式
            this.current = index;
            //显示loading加载框
            var layerNum = layer.load(1);
            //获取工程id
            var id = $("#id").val();
            //获取点击对象
			var actionname = event.target.dataset.actionname;
            vm.selectedAction = actionname;
            //切换blockly控件
            if(vm.project.modelName=="F600"){
                savemyblock("F600");
            }else{
                savemyblock("F400");
            }
            if(!actionname){
                layer.msg("未选中动作组", {icon: 2});
                //返回数据关闭loading
                layer.close(layerNum);
                return;
            }
            //保存上一个动作组
            this.saveBlock(lastAction);
			//查询动作组代码
            $.ajax({
                type: "POST",
                url: baseURL + "ede/group/oneGroup",
                dataType: "json",
                data: {id: id, actionname: actionname},
                success: function (r) {
                    if (r.code === 0) {
                        if (r.group && r.group.xml) {
                            //block加载文件
                            OpenBlocks(r.group.xml);
                        }
                    }else{
                        layer.msg("加载失败", {icon: 2});
                    }
                    //返回数据关闭loading
                    layer.close(layerNum);
                }
            });

            // 阻止冒泡
            event.stopPropagation();
        },

		//添加动作组
        addGroup: function () {
            var id = $("#id").val();
            $.get(baseURL + "ede/group/addGroup?id="+id, function(r){
                vm.getInfo();
            });
        },

		//删除动作组
        delGroup: function () {
            //var lock = false;
            if(!vm.selectedAction){
                layer.alert("请先选择动作组,再点击删除 !");
                return;
            }
            layer.msg('确定要删除选中的记录？', {
                time: 0, //不自动关闭
                btn: ['确定','取消'] //按钮
            }, function() {
                var id = $("#id").val();
                $.ajax({
                    type: "POST",
                    url: baseURL + "ede/group/delGroup",
                    dataType: "json",
                    data: {id: id, actionname: vm.selectedAction},
                    success: function (r) {
                        layer.close(layer.index);
                        vm.getInfo();
                    }
                });
            }, function(){
            });
        },

        //弹出无人机配置窗口
        openFlight: function (index,event) {
            var method = event.target.dataset.method;
            var actionname = event.target.dataset.actionname;
            var id = $("#id").val();
            var x = '0';
            var y = '0';

            //查询无人机位置
            $.ajax({
                type: "POST",
                url: baseURL + "ede/group/getFlight",
                dataType: "json",
                async: false,
                data: {id: id, actionname: actionname},
                success: function (r) {
                    x = r.result.x ? r.result.x : '0';
                    y = r.result.y ? r.result.y : '0';
                }
            });
            //页面层
            layer.open({
                type: 1,
                title: method=='add'?'添加飞行器':'配置飞行器',
                skin: 'layui-layer-rim',
                area: ['400px', '270px'],
                content:
                    '<form class="layui-form"> ' +
                    '  <div style="padding: 10px 30px;" >' +
                    '    <label>初始位置:</label><br/>' +
                    '    <div style="padding: 5px 30px;" >' +
                    '    <input type="hidden" id="flightActionName" value="'+ actionname +'" /> ' +
                    '      X: <input type="number" id="x" name="" placeholder=""  style="width:80px;text-align: center;" value="'+x+'" autocomplete="off" > CM' +
                    '    </div>' +
                    '    <div style="padding: 5px 30px;" >' +
                    '      Y: <input type="number" id="y"  name="" placeholder=""  style="width:80px;text-align: center;"  value="'+y+'" autocomplete="off" > CM' +
                    '    </div>' +
                    '    <div  style="padding: 5px 30px;" >' +
                    '      Z: <input type="number" id="z"  name="" placeholder=""  style="width:80px;text-align: center;"  value="0" autocomplete="off" > CM' +
                    '    </div>' +
                    '  </div>' +
                    '   <input type="button" id="save" data-loading-text="保存中..." value="确定" style="width: 100px; float: right;margin-right: 20px;" class="btn btn-primary" onclick="saveFlight(\''+method+'\')">' +
                    '   <input type="button" value="取消" style="width: 100px; float: right;margin-right: 20px;" class="btn btn-warning" onclick="closeDiv()">' +
                    '</form>'
            });
            // 阻止冒泡
            event.stopPropagation();
        },


        //循环播放
        play: function(){
            var audio = this.$refs.audioExample;
            console.log(vm.playstr);
		    if(vm.playstr=="循环播放"){

                //var begin = vm.beginP;
                //var end = vm.endP;
                console.log(vm.beginP);
                console.log(vm.endP);
                audio.currentTime = vm.beginP;
                audio.play();

                audio.addEventListener('timeupdate', function () {
                    if(vm.playstr == "停止循环"){
                        if(audio.currentTime>vm.endP){
                            audio.currentTime = vm.beginP;
                            audio.play();
                        }
                    }
                }, false);
                vm.playstr = "停止循环";
            }else if(vm.playstr=="停止循环"){
                console.log(2);
                vm.playstr = "循环播放";
            }
        },

        //保存工程
        saveBlock: function (groupname) {
            var isLayer = false;
            var id = $("#id").val();
            var actionname = null;
            //如果groupname有值保存指定的动作组
            if(groupname!=null){
                actionname = groupname;
            }else{
                isLayer = true;
                actionname = vm.selectedAction;
            }
            if(actionname==null || actionname==""){
                return;
            }
            var xml = BlocksToXml();
            console.log(xml);
            vm.group.projectId = id;
            vm.group.py = BlocksToPython();
            vm.group.xml = xml;
            vm.group.name = actionname;
            $.ajax({
                type: "POST",
                url: baseURL + "ede/project/saveProject",
                dataType: "json",
                //async: false,
                data: {projectId: id, py: BlocksToPython(), xml: encodeURIComponent(BlocksToXml()), name: actionname},
                success: function (r) {
                    if (r.code === 0) {
                        if(isLayer){
                            layer.msg("保存成功！", {icon: 1});
                        }
                    } else {
                        layer.alert(r.msg);
                    }
                }
            });
        },
        getProjectById: function (id) {
            $.get(baseURL + "ede/project/info/"+id, function(r){
                //parent.vm.project = r.project;
                vm.project = r.project;
            });
            parent.vm.attrCss();
        },

        //导出动作组
        expGroup: function(){
            var id = $("#id").val();
            var actionname = vm.selectedAction;
            if(actionname==null || actionname==""){
                layer.alert("请选择要导出的动作组");
                return;
            }

            //保存工程
            this.saveBlock(null);
            window.location.href = baseURL + "ede/group/expGroup?projectId="+id+"&name="+actionname;
        },

        //导入
        //impGroup: function () {
        //},
        
        //预览
        preview: function (index,event) {
            //保存工程
            this.saveBlock(null);
            $.getJSON(baseURL+"sys/user/info?_" + $.now(), function (r) {
                console.log(r.user);
                var user = r.user;
                var vip = user.isvip;
                if(vip=="1"){
                    vip="true";
                }else{
                    vip="false";
                }
                //window.open(baseURL + "3d/"+user.userId+"/"+vm.project.project+"/index.html");
                parent.vm.addTab("预览-"+vm.project.project,"webgl/index.html?user="+user.userId+"&vip="+vip+"&project="+vm.project.project);
            });
        },

        //上传音乐
        upMusic: function(){
            //页面层
            layer.open({
                type: 1,
                title: '上传音乐',
                skin: 'layui-layer-rim',
                area: ['400px', '300px'],
                content:
                    '<div class="layui-main" style="width: 380px;text-align: center;margin-top: 5px;">' +
                    '   <form class="layui-form" method="post" action="javascript:;">' +
                    '       <div class="layui-form-item">' +
                    '           ' +
                    '               <div class="layui-inline">' +
                    '                   <div class="layui-upload-drag" id="upload">' +
                    '                       <i class="layui-icon"></i>' +
                    '                       <p>点击上传，或将文件拖拽到此处</p>' +
                    '                   </div>' +
                    '               </div>' +
                    '               <div class="layui-inline" id="upload_preview"></div>' +
                    '       </div>' +
                    '       <div class="layui-inline" >只支持MP3格式</div>' +
                    '   <div class="layui-form-item layui-hide" id="upload_progress">' +
                    '       <label class="layui-form-label"></label>' +
                    '       <div class="layui-input-inline" style="width:90%;">' +
                    '           <div class="layui-progress" lay-showpercent="true" lay-filter="upload_progress">' +
                    '               <div class="layui-progress-bar layui-bg-blue" lay-percent="5%"></div>' +
                    '           </div>' +
                    '       </div>' +
                    '   </div>' +
                    '' +
                    '   </form>'+
                    '</div>'
            });

            var thatLayer = layer;

            layui.use(['element','upload'], function(){
                var upload = layui.upload;
                var element = layui.element;


                //执行实例
                var uploadInst = upload.render({
                    elem: '#upload',
                    exts: 'mp3', //只允许上传压缩文件
                    url: baseURL + "ede/project/uploadMusic?id="+vm.id,
                    before: function(obj) {
                        $("#upload_progress").removeClass("layui-hide");
                    },
                    done: function(r){
                        if(r.code == 0){
                            var audio = vm.$refs.audioExample;
                            audio.src = r.project.music;
                            parent.vm.project.musicName = r.project.musicName;
                            layer.msg("上传成功", {icon: 1});
                            thatLayer.close(thatLayer.index);
                        }else{
                            layer.alert(r.msg);
                        }
                    },
                    progress: function(e , percent) {
                        console.log("进度：" + percent + '%');
                        element.progress('upload_progress',percent  + '%');
                    },
                    error: function(){
                        //请求异常回调
                    }
                });
            });
        }

    }
});

//添加无人机
function saveFlight(method) {
    console.log("---------------");
    var id = $("#id").val();
    var x = $("#x").val();
    var y = $("#y").val();
    var z = $("#z").val();
    var actionname = $("#flightActionName").val();

    $.ajax({
        type: "POST",
        url: baseURL + "ede/group/addFlight",
        dataType: "json",
        data: { method:method, id: id, actionname: actionname, x:x, y:y, z:z },
        success: function (r) {
            console.log(r.group);
            if(r.code=='500'){
                alert(r.msg);
            }
            layer.close(layer.index);
            vm.getInfo();
        }
    });
}

//关闭添加无人机页面
function closeDiv(){
    console.log("-----");
    layer.close(layer.index);
}